<template>
  <div class="rule">

    <el-row class="edit-column">
      <el-button type="primary" icon="el-icon-plus" circle @click="addRule"></el-button>
    </el-row>

    <el-table :data="ruleList" border stripe class="item-table">
      <el-table-column type="index" width="50"></el-table-column>
      <el-table-column align="center" prop="serviceList" label="客服ID列表">
        <template scope="scope">
          <el-tag v-for="service in scope.row.serviceList" size="mini" style="margin: 5px;">{{service.name}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="taskCodeList" label="任务类型列表">
        <template scope="scope">
          <el-tag v-for="type in scope.row.taskTypeList" size="mini" style="color: firebrick; width: 100%">{{type.taskName}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="cron" label="cron时间"></el-table-column>
      <el-table-column align="center" prop="allotment" label="分配个数"></el-table-column>
      <el-table-column align="center" prop="memo" label="备注"></el-table-column>
      <el-table-column align="center" prop="status" label="状态">
        <template scope="scope">
          <el-tag v-if="scope.row.status === 1" size="mini" type="success">运行</el-tag>
          <el-tag v-else-if="scope.row.status === 0" size="mini" type="info">暂停</el-tag>
          <el-tag v-else size="mini" type="warning">未知</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作">
        <template scope="scope">
          <el-button v-if="scope.row.status === 0" type="text" size="mini" style="color: #409EFF" @click="changeTaskRuleStatus(scope.row)">运行</el-button>
          <el-button v-else type="text" size="mini" style="color: #909399" @click="changeTaskRuleStatus(scope.row)">暂停</el-button>

          <el-button type="text" size="mini" style="color: #1E90FF" @click="updateRule(scope.row)">编辑</el-button>
          <el-button type="text" size="mini" style="color: red" @click="deleteTaskRule(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="page">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :page-sizes="[10, 15, 20, 50]"
        :current-page.sync="page.current"
        :page-size="page.size"
        :total="page.total"
        layout="total, sizes, prev, pager, next, jumper">
      </el-pagination>
    </div>

    <!--新增/更新任务规则框-->
    <el-dialog :title=dialogTitle :visible.sync="ruleDialogVisible" width="70%">
      <template>
        <el-row>
          <el-col :span="12">
            <el-transfer v-model="addTaskRuleInfo.ids" :data="personList" @change="personValueChange" :titles="personTableTitle">
            </el-transfer>
            <el-transfer v-model="addTaskRuleInfo.types" :data="taskTypeList" @change="taskTypeValueChange" :titles="taskTypeTableTitle"
                         style="margin-top: 20px">
            </el-transfer>
          </el-col>

          <el-col :span="12">
            <div>
              规则描述：<el-input v-model="addTaskRuleInfo.memo" style="width: 60%;" placeholder="该分配规则描述"></el-input>
            </div>
            <div style="margin-top: 10px">
              分配个数：<el-input v-model="addTaskRuleInfo.allotment" style="width: 60%;" placeholder="平均分配的个数"></el-input>
            </div>
            <div style="margin-top: 10px">
              cron时间：<el-input v-model="addTaskRuleInfo.cron" style="width: 60%;" placeholder="cron表达式 [ 0 0 8 * * ? ] 表示每天8点的任务"></el-input>
              <el-button type="primary" style="margin-left: 5px" @click="cronTextChange(addTaskRuleInfo.cron, true)">验证</el-button>
            </div>
            <div style="margin-top: 20px">
              <p style="color: firebrick">最近5次的运行时间</p>
              <p v-for="text in addTaskRuleInfo.cronText">
                <el-tag size="mini" style="color: firebrick; margin-top: 5px">{{text}}</el-tag>
              </p>
            </div>
          </el-col>
        </el-row>

        <span slot="footer" class="dialog-footer">
          <el-button @click="ruleDialogVisible = false; addTaskRuleInfo = {}">取 消</el-button>
          <el-button type="primary" @click="clickTaskRule">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
  export default {
    components: {},
    name: 'Rule',
    data () {
      return {
        addRuleDialogTitle: '新增分配规则',
        updateRuleDialogTitle: '更新分配规则',
        ruleDialogVisible: false,
        addRuleInfo: {},
        dialogTitle: '',

        ruleList: [],
        page: {
          current: 1,
          size: 10,
          total: 0
        },

        // 待分配客服人员名单
        personList: [],
        personTableTitle: ['待分配人员列表', '已分配人员列表'],
        taskTypeList: [],
        taskTypeTableTitle: ['待分配类型列表', '已分配类型列表'],

        addIds: [],
        addTypes: [],
        addTaskRuleInfo: {
          id: '',
          status: '',
          ids: [],
          types: [],
          cron: '',
          memo: '',
          allotment: '', // 分配个数
          cronText: []
        },
      }
    },
    created() {
      this.loadRuleList();
    },
    methods: {
      /** 页数修改处理 */
      handleSizeChange(val) {
        this.page.current = 1;
        this.page.size = val;
        this.loadRuleList();
      },
      handleCurrentChange() {
        this.loadRuleList();
      },
      cronTextChange(cron, show) {
        this.addTaskRuleInfo.cronText = [];
//        let cron = this.addTaskRuleInfo.cron;
        if(typeof cron === "undefined" || cron === null || cron === "") {
          this.$message.error("cron表达式为空");
          return;
        }

        this.$http.put("/api/rule/check/cron", { cron: cron }, {emulateJSON: true}).then((res) => {
          if (!this.checkResponse(res)) {
            return;
          }

//          console.info(res.data.data);
          this.addTaskRuleInfo.cronText = res.data.data;
          if (show) {
            this.$message.success("cron表达式正确");
          }
        }).catch(e => { this.messageException(e); });
      },

      /** 添加任务规则 */
      clickTaskRule() {
        if (this.dialogTitle === this.addRuleDialogTitle) {
          this.$http.post("/api/rule", {
            allotServiceId:  this.addTaskRuleInfo.ids.join(','),
            allotTaskCode:   this.addTaskRuleInfo.types.join(','),
            autoAllotTime: this.addTaskRuleInfo.cron,
            allotment: this.addTaskRuleInfo.allotment,
            memo:   this.addTaskRuleInfo.memo
          }, {emulateJSON: true}).then((res) => {
            if (!this.checkResponse(res)) {
              return;
            }

            this.$message.success("添加任务规则成功");
            this.ruleDialogVisible = false;
            this.addTaskRuleInfo = {};
            this.loadRuleList();
          }).catch(e => { this.messageException(e); });
        } else if (this.dialogTitle === this.updateRuleDialogTitle) {
          this.$http.put("/api/rule", {
            id: this.addTaskRuleInfo.id,
            status: this.addTaskRuleInfo.status,
            allotServiceId:  this.addTaskRuleInfo.ids.join(','),
            allotTaskCode:   this.addTaskRuleInfo.types.join(','),
            autoAllotTime: this.addTaskRuleInfo.cron,
            allotment: this.addTaskRuleInfo.allotment,
            memo:   this.addTaskRuleInfo.memo,
          }, {emulateJSON: true}).then((res) => {
            if (!this.checkResponse(res)) {
              return;
            }

            this.$message.success("更新任务规则成功");
            this.ruleDialogVisible = false;
            this.addTaskRuleInfo = {};
            this.loadRuleList();
          }).catch(e => { this.messageException(e); });
        } else {
          this.$message.error("操作错误");
        }
      },
      changeTaskRuleStatus(taskRule) {
        if (taskRule.status === 1) {
          taskRule.status = 0;
        } else if (taskRule.status === 0) {
          taskRule.status = 1;
        } else {
          return;
        }

        this.$http.put("/api/rule/status/" + taskRule.status + '/' + taskRule.id, {}, {emulateJSON: true}).then((res) => {
          if (!this.checkResponse(res)) {
            return;
          }

          this.$message.success("更新任务状态成功");
          this.loadRuleList();
        }).catch(e => { this.messageException(e); });
      },

      /** 添加规则时 客服人员列表和任务类型列表更新方法 */
      personValueChange() {
      },
      taskTypeValueChange() {
      },
      /** 添加规则时 加载客服人员列表 */
      loadPersonList() {
        this.$http.get("/api/customer/list",{emulateJSON: true}).then((res) => {
          if (!this.checkResponse(res)) {
            return;
          }

          let personList = res.data.data;
          this.personList = [];
          for (let i = 0; i <= personList.length; i++) {
            let person = personList[i];
            this.personList.push({
              key: person.id,
              label: person.name,
              disabled: false
            });
          }
        }).catch((e) => {});
      },
      /** 添加规则时 加载任务类型列表 */
      loadTaskTypeList() {
        this.$http.get("/api/type/list",{emulateJSON: true}).then((res) => {
          if (!this.checkResponse(res)) {
            return;
          }

          let taskTypeList = res.data.data;
          this.taskTypeList = [];
          for (let i = 0; i < taskTypeList.length; i++) {
            let taskType = taskTypeList[i];
            this.taskTypeList.push({
              key: taskType.taskCode,
              label: taskType.taskName,
              disabled: false
            });
          }
        }).catch((e) => {});
      },
      addRule() {
        this.addTaskRuleInfo = {};
        this.loadPersonList();
        this.loadTaskTypeList();

        this.dialogTitle = this.addRuleDialogTitle;
        this.ruleDialogVisible = true;
      },
      updateRule(taskRule) {
        this.loadPersonList();
        this.loadTaskTypeList();
        this.cronTextChange(taskRule.cron);

        this.addTaskRuleInfo.id = taskRule.id;
        this.addTaskRuleInfo.status = taskRule.status;
        this.addTaskRuleInfo.ids = [];
        for (let i = 0; i < taskRule.serviceList.length; i++) {
          this.addTaskRuleInfo.ids.push(taskRule.serviceList[i].id);
        }
        this.addTaskRuleInfo.types = [];
        for (let i = 0; i < taskRule.taskTypeList.length; i++) {
          this.addTaskRuleInfo.types.push(taskRule.taskTypeList[i].taskCode);
        }
        this.addTaskRuleInfo.cron = taskRule.cron;
        this.addTaskRuleInfo.memo = taskRule.memo;
        this.addTaskRuleInfo.allotment = taskRule.allotment;

        this.dialogTitle = this.updateRuleDialogTitle;
        this.ruleDialogVisible = true;
      },
      deleteTaskRule(taskRule) {
        this.$confirm('此操作将删除该分配规则, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http.put('/api/rule/delete', {
            id: taskRule.id,
            allotServiceId:  taskRule.serviceIdList,
            allotTaskCode:   taskRule.taskCodeList,
            autoAllotTime: taskRule.cron,
            allotment: taskRule.allotment,
            memo:   taskRule.memo,
          }, {emulateJSON: true}).then((res) => {
            if (!this.checkResponse(res)) {
              return;
            }

            this.$message.success('删除成功!');
            this.loadRuleList();
          });

        }).catch((e) => {
          this.$message.success(e);
        });
      },

      loadRuleList() {
        this.$http.post("/api/rule/page/list", {
          current: this.page.current,
          size: this.page.size
        },{emulateJSON: true}).then((res) => {
          if (!this.checkResponse(res)) {
            return;
          }

          let page = res.body.data;
          this.page.total = page.total;
          this.ruleList = page.data;

        }).catch((e) => {
          this.messageException(e);
        });
      }
    },
  }
</script>

<style lang="less" scoped>
  .rule {
  }
</style>
